package com.lagace.spark.twitter.local;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import org.jivesoftware.Spark;
import org.jivesoftware.spark.util.log.Log;

public class TwitterSettingsManager {

    private static LocalTwitterPreferences localPreferences;
    private static boolean fileExists = false;

    private TwitterSettingsManager() {
    }

    public static LocalTwitterPreferences getLocalTwitterPreferences() {
        if(localPreferences != null){
            return localPreferences;
        }

        if (!fileExists) {
            fileExists = exists();
        }

        if (!fileExists && localPreferences == null) {
            localPreferences = new LocalTwitterPreferences();
            saveSettings();
        }

        if (localPreferences == null) {
            getSettingsFile();
            localPreferences = load();
        }

        return localPreferences;
    }

    public static void saveSettings() {
        final Properties props = localPreferences.getProperties();

        try {
            props.store(new FileOutputStream(getSettingsFile()), "Spark Settings");
        }
        catch (Exception e) {
            Log.error("Error saving settings.", e);
        }
    }

    public static boolean exists() {
        return getSettingsFile().exists();
    }

    public static File getSettingsFile() {
        File file = new File(Spark.getUserHome());
        if (!file.exists()) {
            file.mkdirs();
        }
        return new File(file, "twitter.spark.properties");
    }

    private static LocalTwitterPreferences load() {
        final Properties props = new Properties();
        try {
            props.load(new FileInputStream(getSettingsFile()));
        }
        catch (IOException e) {
            Log.error(e);
            return new LocalTwitterPreferences();
        }

        File globalSettingsFile = new File("twitter.spark.properties");
        if (globalSettingsFile.exists()) {
            try {
                props.load(new FileInputStream(globalSettingsFile));
            } catch (IOException e) {
                Log.error(e);
            }
        }

        return new LocalTwitterPreferences(props);
    }
}

